<#
Purpose: Windows wrapper to execute existing Bash (.sh) scripts.
Usage:
  powershell -ExecutionPolicy Bypass -File scripts\windows\custom_init.ps1 --langs=java,python --style=mimic
Notes:
  - Detects Bash via PATH or Git for Windows; falls back to common install paths.
  - Forwards all arguments to the underlying Bash script unchanged.
  - Avoids hardcoding any privacy-sensitive configuration.
#>

param(
  [Parameter(Mandatory=$true)][string]$ScriptRelativePath,
  [Parameter()][string[]]$ScriptArgs
)

function Find-Bash {
  $candidates = @(
    'bash',
    'C:\\Program Files\\Git\\bin\\bash.exe',
    'C:\\Program Files\\Git\\usr\\bin\\bash.exe',
    'C:\\Program Files (x86)\\Git\\bin\\bash.exe'
  )
  foreach ($c in $candidates) {
    try {
      $cmd = Get-Command $c -ErrorAction SilentlyContinue
      if ($cmd) { return $cmd.Path }
    } catch {}
  }
  return $null
}

$bashExe = Find-Bash
if (-not $bashExe) {
  Write-Error 'Bash not found. Please install Git for Windows (includes Bash) or add bash to PATH.'
  exit 1
}

# Resolve repo root from this script location: scripts/windows -> project root is two levels up
$repoRoot = (Resolve-Path "$PSScriptRoot\..\..\..").Path
# 从 config/rules.env 读取可配置的框架目录名（默认 AIDevFlow）
$envFile = Join-Path $repoRoot 'config/rules.env'
$frameworkDir = 'AIDevFlow'
if (Test-Path $envFile) {
  $lines = Get-Content -Path $envFile -ErrorAction SilentlyContinue
  foreach ($line in $lines) {
    if ($line -match '^[\s#]*FRAMEWORK_DIR_NAME\s*=\s*(.+)\s*$') {
      $frameworkDir = $Matches[1].Trim()
      break
    }
  }
}
$scriptPath = Join-Path $repoRoot ($frameworkDir + "\\scripts\\" + $ScriptRelativePath)

if (-not (Test-Path $scriptPath)) {
  Write-Error "Target script not found: $scriptPath"
  exit 2
}

# Execute bash script and forward args
& $bashExe $scriptPath @ScriptArgs
$exitCode = $LASTEXITCODE
exit $exitCode
